using System;
using System.Text;
using System.Net;
using Instedd.Labs.Geo.Library.Kml;
using System.IO;

namespace Instedd.Labs.Geo.Library.GPS
{
    public sealed class GoogleGeoCoder : IGeoCoder
    {
        String googleKey;
        bool initialized = false;
        String GoogleGeoCoderUrl = "http://maps.google.com/maps/geo?q={0}&output=csv&key={1}";

        #region IGeoCoder Members

        public Instedd.Labs.Geo.Library.Kml.LatLong GetLatLongFromPostalAddress(string postalAddress)
        {
            if (!initialized)
            {
                // TODO: move to SR
                throw new Exception("GoogleGeoCoder needs to be initialized before used");
            }

            String url = String.Format(GoogleGeoCoderUrl, postalAddress, googleKey);
            WebRequest webRequest = HttpWebRequest.Create(url);
            HttpWebResponse webResponse = webRequest.GetResponse() as HttpWebResponse;

            if (webResponse.StatusCode != HttpStatusCode.OK)
            {
                return null;
            }

            StreamReader webstream = new StreamReader(webResponse.GetResponseStream(), Encoding.ASCII);
            String temp; StringBuilder sb = new StringBuilder();
            while ((temp = webstream.ReadLine()) != null)
            {
                sb.Append(temp);
            }

            String[] parts = sb.ToString().Split(',');
            if (parts[0] == "200")
            {
                return LatLong.Parse(parts[2], parts[3]);
            }

            return null;
        }

        public void Initialize(object initData)
        {
            googleKey = initData as String;

            if (String.IsNullOrEmpty(googleKey))
            {
                throw new ArgumentNullException("initData");
            }

            initialized = true;
        }

        #endregion
    }
}
